<template>
  <div class="container">
    <el-row justify="center">
      <el-col :span="24" style="text-align: center;">
        <span class="title">欢迎使用[{{ globalSubTitle }}]检测系统</span>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12" style="text-align: center;">
        <el-card style="height: 350px;max-height: 350px;">
          <el-upload
              ref="upload"
              class="upload-demo"
              action="/api/image_recognition/uploadImage/"
              :on-success="handleUploadSuccess"
              drag
              multiple
              :limit="1"
              :on-exceed="handleExceed"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到这 / <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                仅支持上传jpg/png文件，且不超过5MB
              </div>
            </template>
          </el-upload>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card style="height: 350px;max-height: 350px;">
          <el-descriptions title="最新识别结果" column="2" border direction="vertical" v-if="nowRecord">
            <el-descriptions-item label="识别图片" :rowspan="3" align="center">
              <el-image
                  v-if="nowRecord"
                  class="recordImage"
                  :src="'api/'+nowRecord.upload_image"
                  fit="cover"
                  preview-src-list="[nowRecord.upload_image]"
              />
            </el-descriptions-item>
            <el-descriptions-item label="时间" align="center">{{ formatTime(nowRecord?.time) }}</el-descriptions-item>
            <el-descriptions-item label="置信度" align="center">{{ handleDecimal(Number(nowRecord?.confidence)) }}%</el-descriptions-item>
            <el-descriptions-item label="识别结果" align="center">{{ nowRecord?.result_type }}</el-descriptions-item>
          </el-descriptions>
          <el-empty description="还没有识别任何图片哦~" v-else/>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card >
          <hz-echarts-line-base id="line1" ref="line1" style="min-height: 300px;max-height: 300px;"/>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <hz-echarts-pie-base id="pie1" ref="pie1" style="min-height: 300px;max-height: 300px;"/>
        </el-card>
      </el-col>
    </el-row>

    <el-row style="margin-top: 20px;">
      <el-card v-for="record in recognitionRecord" :key="record.id" style="margin-bottom: 20px;margin-left: 30px">
        <div class="collapse-header">
          <span class="record-time">{{ formatTime(record.time) }}</span>
          <el-badge class="badge" :value="handleDecimal(Number(record.confidence)) + '%'" />
        </div>
        <div class="collapse-header">
          <span class="record-result">{{ record.result_type}}</span>
        </div>
        <el-image
            v-if="record.upload_image"
            class="record-image"
            :src="'api/'+record.upload_image"
            fit="cover"
            preview-src-list="[record.upload_image]"
        />
      </el-card>
    </el-row>

  </div>
</template>

<script setup lang="ts">
import {ref} from "vue";
import { UploadFilled} from '@element-plus/icons-vue'
import {genFileId, UploadInstance, UploadProps, UploadRawFile} from "element-plus";
import {useMessage} from "/@hooks/message";
import {
  getImageRecognitionList,
  getImageRecognitionStatistics
} from "/@api/image_recognition/hz-system-image-recognition-api";

const globalSubTitle = ref(import.meta.env.VITE_GLOBAL_SUBTITLE?.trim() || 'HZSYSTEM');

interface ImageRecord {
  id: number;
  time: string;
  upload_image: string;
  confidence: string;
  result_type: string;
}

const upload = ref<UploadInstance>()
const recognitionRecord = ref<ImageRecord[]>([]);
const nowRecord = ref<ImageRecord | null>(null);

const pie1 = ref(null);
const line1 = ref(null);

const pageConfig = ref({
  page: 1,
  pageSize: 10,
  total: 0,
});


onMounted(() => {
  loadYoLoRecognitionRecord();
  loadYoLoRecognitionStatistics();
});

const loadYoLoRecognitionRecord = async () => {
  const response = await getImageRecognitionList({
    page: pageConfig.value.page,
    pageSize: pageConfig.value.pageSize,
  });
  recognitionRecord.value = response.data.record;
};

const loadYoLoRecognitionStatistics = async () => {
  const response = await getImageRecognitionStatistics();

  pie1.value?.refreshChart({
    title: '识别类型',
    subtext: '识别类型统计',
    yData: parseToPie(response.data?.resultTypeCount || {})
  });

  const lineData = parseToLine(response.data?.resultTimeCount || {})
  console.log('lineData', lineData)

  line1.value?.refreshChart({
    title: '识别次数/分钟',
    xData: lineData.xData,
    yData: lineData.yData
  });

};

const handleUploadSuccess = (response: any, file: any, fileList: any) => {
  nowRecord.value = response.data
  loadYoLoRecognitionRecord();
  loadYoLoRecognitionStatistics();
  useMessage().success('图片识别成功')
}

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
  // 执行上传
  upload.value!.submit()
}

const parseToPie = (data: any) => {
  return data.map((item: any) => {
    return {
      name: item.result_type,
      value: item.count
    }
  })
}

const parseToLine = (data: any) => {
  const xData: string[] = []
  const yData: number[] = []
  data.forEach((item: any) => {
    xData.push(item.time)
    yData.push(item.count)
  })
  return {
    xData,
    yData
  }
}

// 处理小数，保留两位小数 0.9999511241912842 => 0.99
const handleDecimal = (num: number) => {
  // 先*100
  const numStr = (num * 100).toString()
  // 找到小数点的位置
  const index = numStr.indexOf('.')
  // 截取小数点后两位
  return numStr.slice(0, index + 3)
}

// 格式化显示时间 2025-03-03T23:39:27.918780 => 2025-03-03 23:39:27
const formatTime = (time: string) => {
  return time.split('T').join(' ').split('.')[0]
}

</script>

<style scoped lang="css">
.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.title {
  font-size: 28px;
  color: #303133;
  letter-spacing: 1.2px;
  margin: 20px 0;
  display: inline-block;
  background: linear-gradient(45deg, #409eff, #79bbff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.upload-demo {
  margin: 30px 0;
}


.recordImage{
  width: 150px;
  height: 150px;
}


.collapse-header {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 12px 0;
}

.record-time {
  color: #606266;
  font-size: 14px;
}

.badge {
  margin-left: auto;
}

.record-image {
  width: 200px;
  height: 200px;
  border-radius: 6px;
  transition: transform 0.3s;
  cursor: pointer;
}

.record-image:hover {
  transform: scale(1.05);
}

.record-result {
  color: #606266;
  font-size: 24px;
}

</style>
